//
//  ProfileView.swift
//  ShouChong
//
//  Created by yw on 2024/8/12.
//

import SwiftUI
import ZLPhotoBrowser

struct ProfileView: View {
    @ObservedObject var vm:UserViewModel = UserViewModel()
    @AppStorage("curren_main_color") var currentMainColor = "color_main_01"
    @State private var showImageSheet:Bool  = false
    @State var showAppSelecItem:ProfileModel?
    @State private var showTest:Bool = false
    @AppStorage("user_avator") var userAvatar = "user_header_01"
    @AppStorage("user_avator_base64") var avatorBase64 = ""
    
    @AppStorage("user_name") var userName = ""
    @State var showUerNameSheet:Bool = false
    @State var showChangeColorSheet:Bool = false
    @State var showAboutSheet:Bool = false
    @State var showBindAccountSheet:Bool = false
    @State var showVipSheet:Bool = false
    @AppStorage("login_token") var loginToken:String = ""
    struct ProfileModel:Identifiable {
        var id:String = UUID().uuidString
        var name:String
        var icon:String
        var detail:String
        var showArrow:Bool = true
    }
    @State private var innerColor:String = "color_main_01"

    
    @State var list:[[ProfileModel]] = [
        [
            ProfileModel(name: "内置头像选择", icon: "person.fill", detail: ""),
            ProfileModel(name: "系统相册选择", icon: "photo.fill", detail: ""),
            ProfileModel(name: "绑定账号", icon: "person.crop.circle.fill", detail: ""),
            
        ],
        [
            ProfileModel(name: "成为会员", icon: "gift.fill", detail: ""),
            ProfileModel(name: "修改昵称", icon: "eraser.fill", detail: ""),
            ProfileModel(name: "修改主题色", icon: "paintbrush.fill", detail: ""),
            ProfileModel(name: "关于我们", icon: "person.2.fill", detail: ""),
            ProfileModel(name: "给个好评", icon: "heart.fill", detail: "大佬们请理性打分，谢谢"),
            ProfileModel(name: "分享App", icon: "square.and.arrow.up.fill", detail: "")
        ],
        
        [
            ProfileModel(name: "Chat-AI", icon: "", detail: "体验人工智能AI🤖"),
            ProfileModel(name: "今日不吸烟", icon: "", detail: "帮您戒除香烟🚬"),
        ],
        
        
    ]
    
    
    var body: some View {
        GeometryReader(content: { geometry in
            ScrollView {
                headerView
                    .cornerRadius(20)
                    .padding(.vertical,20)
                    .padding(.horizontal,16)
                sectionView
                    .padding(.horizontal,16)
                ShakeButton(label: Text("退出登录").modifier(MainButtonModifier(width: kScreenWidth - 40))) {
                    logout()
                }
                .padding(.top,60)
                .padding(.bottom,4)
                ShakeButton(label: Text("注销账号").modifier(MainTextModifier(fontSize: 12, fontWeight: .light, foreColor: Color("color_text_black")))) {
                    removeAccount()
                }
                   
            }
            .sheet(item: self.$showAppSelecItem) {
                vm.getUserInfo()
                
            } content: { id in
                AvatarChooseView()
            }
            .sheet(isPresented: $showUerNameSheet, onDismiss: {
                vm.getUserInfo()
            }, content: {
                ChangeNameView()
            })
            .sheet(isPresented: $showChangeColorSheet, onDismiss: {
                
            }, content: {
                ChangeColorView()
            })
            .sheet(isPresented: $showAboutSheet, onDismiss: {
                
            }, content: {
                AboutView()
            })
            .sheet(isPresented: $showBindAccountSheet, content: {
                BindAccountView()
            })
            .sheet(isPresented: $showVipSheet, content: {
                VIPView()
            })
            
           
        })
        .onAppear{
            innerColor = currentMainColor
        }
        .onChange(of: currentMainColor) { oldValue, newValue in
            print(oldValue)
            print(newValue)
            innerColor = newValue
        }
        
    }
    
    var sectionView:some View {
        ForEach(0..<list.count,id: \.self) { index in
            if index == 0 {
                HStack {
                    Text("账号设置")
                        .modifier(MainTextModifier(fontSize: 12, fontWeight: .regular, foreColor: Color("color_gray")))
                    Spacer()
                }.padding(.horizontal,16)
                    .offset(y:8)
            }
            if index == 1 {
                HStack {
                    Text("其他设置")
                        .modifier(MainTextModifier(fontSize: 12, fontWeight: .regular, foreColor: Color("color_gray")))
                    Spacer()
                }.padding(.horizontal,16)
                    .offset(y:8)
            }
            if index == list.count - 1 {
                HStack {
                    Text("更多App")
                        .modifier(MainTextModifier(fontSize: 12, fontWeight: .regular, foreColor: Color("color_gray")))
                    Spacer()
                }.padding(.horizontal,16)
                    .offset(y:8)
            }
            VStack(spacing:0) {
                ForEach(list[index]) { item in
                    HStack(spacing:0) {
                        if !item.icon.isEmpty {
                            Image(systemName: item.icon)
                                .resizable()
                                .aspectRatio(contentMode: .fill)
                                .frame(width: 16,height: 16)
                                .padding(.leading,16)
                                .padding(.trailing,8)
                                .foregroundColor(Color(innerColor))
                        }
                        Text(item.name)
                            .modifier(MainTextModifier(fontSize: 14, fontWeight: .medium, foreColor: Color("color_text_black")))
                            .padding(.leading,item.icon.isEmpty ? 16:0)
                        Spacer()
                        if item.detail.count != 0 {
                            Text(item.detail)
                                .modifier(MainTextModifier(fontSize: 12, fontWeight: .regular, foreColor: Color("color_gray")))
                        }
                        if item.showArrow {
                            Image(systemName: "chevron.right")
                                .foregroundColor(Color("color_select"))
                                .padding(.trailing,16)
                                .padding(.leading,4)
                        }
                    }
                    .frame(height:54)
                    .background(Color("color_white"))
                    .contentShape(Rectangle())
                    .onTapGesture {
                        tapGes(item: item)
                    }
                }
            }
            .cornerRadius(16)
            .padding(.vertical,10)
            
        }
            
    }
    
    var headerView: some View {
        HStack {
            Image(uiImage:(vm.model.image.imageFromBase64 ?? UIImage(named: "user_header_01")!))
                .resizable()
                .frame(width:72,height: 72)
                .cornerRadius(36)
                .padding(.leading,16)

            Text(vm.model.name)
                .modifier(MainTextModifier(fontSize: 16, fontWeight: .bold, foreColor: Color("color_text_black")))
            Spacer()
//            Image(systemName: "chevron.right")
//                .resizable()
//                .frame(width: ,height: 24)
//                .foregroundColor(Color("color_select"))
//                .padding(.trailing,16)
        }
        .padding(.vertical,10)
        .background(.white)
        .contentShape(Rectangle())
        .onTapGesture {
            
        }
        
    }
    
    private func tapGes(item:ProfileModel) {
        let generator = UIImpactFeedbackGenerator(style: .light)
        generator.prepare()
        generator.impactOccurred()
        if item.name == "内置头像选择" {
            showAppSelecItem = item
        } else if item.name == "系统相册选择" {
            selectPhotos()
        } else if item.name == "修改昵称" {
            showUerNameSheet.toggle()
        } else if item.name == "修改日记名称" {
            
        } else if item.name == "修改主题色" {
            showChangeColorSheet.toggle()
        } else if item.name == "关于我们" {
            showAboutSheet.toggle()
        } else if item.name == "给个好评" {
            goodComment()
        } else if item.name == "Chat-AI" {
            jumpToAppStore(appId: "1670543338")
        } else if item.name == "今日不吸烟" {
            jumpToAppStore(appId: "6451037923")
        } else if item.name == "分享App" {
            shareApp()
        } else if item.name == "绑定账号" {
            showBindAccountSheet.toggle()
        } else if item.name == "成为会员" {
            showVipSheet.toggle()
        }
    }
    
    private func logout() {
        let tipsView = TipsView.createTipsView(title: "提示", content: "您是否确认退出登录？",showFeelingView: false) {tag in
            loginToken = ""
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                UIApplication.shared.windows.first?.rootViewController = WelcomeViewController()
            }
        } cancelAction: {
            
        }
        tipsView.show(.sheet, backgoundTapDismissEnable: false)
    }
    
    private func removeAccount() {
        let tipsView = TipsView.createTipsView(title: "提示", content: "您是否确认注销账号？",showFeelingView: false) {tag in
            vm.removeAccount {
                loginToken = ""
                DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                    UIApplication.shared.windows.first?.rootViewController = WelcomeViewController()
                }
            }
        } cancelAction: {
            
        }
        tipsView.show(.sheet, backgoundTapDismissEnable: false)
    }
    
    private func shareApp() {
        let title = NSLocalizedString("撸了么", comment: "")
        let appUrl = "itms-apps://itunes.apple.com/app/id\(kAPPId)"
        let image = UIImage(named: "logo")
        let url = URL(string: appUrl)
        let arr:[Any] = [title,image!,url!]
        let vc = UIActivityViewController(activityItems: arr, applicationActivities: nil)
        vc.excludedActivityTypes = [.airDrop,.openInIBooks,.addToReadingList,]
        if let root = UIApplication.shared.windows.first?.rootViewController {
            root.present(vc, animated: true)
        }
    }
    
    private func jumpToAppStore(appId:String) {
        let url = URL(string:"itms-apps://itunes.apple.com/app/\(appId)")
        if !UIApplication.shared.canOpenURL(url!) {
            // 不能跳转就不要往下执行了
            return
        }
        UIApplication.shared.open(url!, options: [:]) { (success) in
            if (success) {
                print("10以后可以跳转url")
            }else{
                print("10以后不能完成跳转")
            }
        }
    }
    
    private func goodComment() {
        let openStr = "itms-apps://itunes.apple.com/app/id\(kAPPId)?action=write-review"
        if let url = URL(string: openStr) {
            if UIApplication.shared.canOpenURL(url) {
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                } else {
                    UIApplication.shared.canOpenURL(url)
                }
            } else {
                print("无法打开链接")
            }
        }
    }
    
    private func selectPhotos() {
            let scene = UIApplication.shared.connectedScenes.first
            let root = (scene as? UIWindowScene)?.windows.first?.rootViewController
            if root != nil {
                ZLPhotoConfiguration.default().maxSelectCount = 1
                ZLPhotoConfiguration.default().allowEditVideo = false
                ZLPhotoConfiguration.default().allowSelectVideo = false
                ZLPhotoConfiguration.default().allowSelectVideo = false
                ZLPhotoConfiguration.default().allowSelectLivePhoto = false
                let ac = ZLPhotoPreviewSheet()
                ac.selectImageBlock = {  results,isOriginal in
                    let scaleImage = results.first?.image.scale(newWidth: 100)
                    guard let imageStr = scaleImage?.base64 else {
                        YWToast.show(text: "获取图片失败")
                        return
                    }
                    let sendData = [
                        "image":imageStr
                    ]
                    YWNetworkTool.share().requestJson(url: "info/editNNUserImage", parameters: sendData) { res in
                        DPrint(res)
                        avatorBase64 = imageStr
//                        userAvatar = "user_header_01"
                        vm.getUserInfo()
//                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
//                            presentationMode.wrappedValue.dismiss()
//                        }
                    } responseFailBlock: { error, code in
                        YWToast.show(text: "上传头像失败，请稍后重试")
                    }
                }
                ac.showPhotoLibrary(sender: root!)
            }
        }
}


